package com.fancy.projecty.config.shiro;

import com.fancy.projecty.util.JwtTokenUtil;
import com.fancy.projecty.util.TokenExceptionUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

/**
 * 暂时没用到!!!!!!!!!!!!!!
 * <p>
 * <p>
 * jwt过滤器
 * 参考:
 * https://blog.csdn.net/dghkgjlh/article/details/90551285
 * 但是那个写的有点问题, 建议不要全部参考,,只是参考部分的3
 */
public class JWTAuthFilter extends FormAuthenticationFilter {


	/**
	 * 判断token是否为空、过期
	 *
	 * @param request
	 * @param response
	 * @param mappedValue
	 * @return
	 */
	@SneakyThrows
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		String jwtToken = httpServletRequest.getHeader("jwtToken");

		if (StringUtils.isEmpty(jwtToken)) {


			throw new TokenExceptionUtil("没有携带token");
		}

		if (StringUtils.isBlank(jwtToken)) {
			throw new TokenExceptionUtil("token不能为空");
		}

		try {
			//解析失败说明token过期了
			JwtTokenUtil.parseToken(jwtToken);
			System.err.println("---通过了token验证-----------------------------------------------");
		} catch (Exception e) {
			System.err.println("---没有通过token验证-----------------------------------------------");
			throw new TokenExceptionUtil("token过期了");
		}

		return true;  // 必须reture true  , 如果不 返回true 就是不允许访问请求.
	}

	/**
	 * 上面的方法如果返回false,则接下来会执行这个方法,如果返回为true,则不会执行这个方法
	 * 判断是否为登录url,进一步判断请求是不是post
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		if (isLoginRequest(request, response)) {
			if (isLoginSubmission(request, response)) {
				return true;
			}
		}
		return false;
	}
}